# -*- coding: utf-8 -*-
import base64
import datetime
import time
from urllib import parse
from urllib.parse import urlencode
import json
import requests
import rsa
import random
import binascii
import re

'''headers'''
headers = {
    # 'Host':	'login.sina.com.cn',
    # 'Connection':	'keep-alive',
    # 'Content-Length':	'624',
    #  'Cache-Control':	'max-age=0',
    # 'Origin'	:'https://weibo.com',
    # 'Upgrade-Insecure-Requests':	'1',
    # 'DNT':	'1',
    # 'Content-Type':	'application/x-www-form-urlencoded',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36',
    # 'Accept':	'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    # 'Referer':	'https://weibo.com/',
    # 'Accept-Encoding':	'gzip, deflate, br',
    # 'Accept-Language':	'zh-CN,zh;q=0.9,en;q=0.8',
    # 'Cookie':	'login=13a0857768fc0c0abafd3d70c0f4538a; SINAGLOBAL=172.16.138.138_1541038556.17115; Apache=172.16.138.138_1541038556.17118; SCF=Ak293onlvowNUZWlI1oLUXcE0wArmO0a9MI21yqrI9z2WpS1ylInhlUjEN9Z4fJ97upo_ry9Qe6mtvO1pSY_jpM.; SUB=_2AkMshu0hdcPxrAZVmf4dzGrrZY5H-jyfU4TXAn7tJhMyAhh77gstqSVutBF-XKfjkkrL3alAhn_FrXpvN8SG_XDW; SUBP=0033WrSXqPxfM72wWs9jqgMF55529P9D9Whh4h34Gi_jawDnV6vY-g4n5JpVF02ReoefShBpeK2p; ULOGIN_IMG=tc-f1d1b49c8fef60b0962feaeaac73a0090ada',

}




def start_requests(session):  #构造出请求5个参数url
    url = 'https://login.sina.com.cn/sso/prelogin.php?'
    su = base64.b64encode(b'18838828864')
    ser_time = int(time.time() * 1000)
    param = {'entry': "weibo", 'callback': "sinaSSOController.preloginCallBack", 'su': su, 'rsakt': "mod",
             'checkpin': '1', 'client': 'ssologin.js(v1.4.19)', '_': ser_time}
    pre_url = url + urlencode(param)
    print(pre_url)
    html = session.get(pre_url)
    print(html.text)
    return session,html

def start_requests_2(session,formdata):
    print(formdata)
    url = f'https://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.19)&_={int(time.time() * 1000)}'
    print(url)
    html = session.post(url,data=formdata)
    print(html.status_code)
    print(html.text)
    return session,html

def start_requsets_3(session,finalurl):
    html = session.get(finalurl)
    print(html.text)
    return session,html
def get_password(servertime, nonce, password, pubkey):
    # print(password)
    rsaPublickey = int(pubkey, 16)
    para2 = int('10001', 16)
    key = rsa.PublicKey(rsaPublickey, para2)  # 创建公钥
    message = str(servertime) + '\t' + str(nonce) + '\n' + str(password)  # 拼接明文 js加密文件中得到
    # print(message)
    message = bytes(message, encoding="utf-8")
    passwd = rsa.encrypt(message, key)  # 加密
    passwd = binascii.b2a_hex(passwd)  # 将加密信息转换为16进制。
    # print(passwd)
    return passwd


def getform(html):
    print(123)
    res_text = html.text
    res_text = res_text.strip('sinaSSOController.preloginCallBack')
    res_text = res_text.strip('(')
    res_text = res_text.strip(')')
    res_text = json.loads(res_text)
    login_url = 'https://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.19)'

    nonce = res_text['nonce']
    pcid = res_text['pcid']
    servertime = res_text['servertime']
    rsakv = res_text['rsakv']
    pubkey = res_text['pubkey']
    su = base64.b64encode(b'18838828864')
    password = '1987wade'
    sp = get_password(servertime, nonce, password, pubkey)

    FormData = {
        'entry': 'weibo',
        'gateway': '1',
        'from': '',
        'savestate': '0',
        'qrcode_flag': 'false',
        'useticket': '1',
        'pagerefer': 'https://login.sina.com.cn/crossdomain2.php?action=logout&r=https%3A%2F%2Fpassport.weibo.com%2Fwbsso%2Flogout%3Fr%3Dhttps%253A%252F%252Fweibo.com%26returntype%3D1',
        'pcid': pcid,
        'door': '',
        'vsnf': '1',
        'su': su,
        'service': 'miniblog',
        'servertime': str(servertime),
        'nonce': nonce,
        'pwencode': 'rsa2',
        'rsakv': '1330428213',
        'sp': sp,
        'sr': '1440*900',
        'encoding': 'UTF-8',
        'prelt': str(random.randint(20, 200)),
        'url': 'https://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack',
        'returntype': 'META',
    }
    return FormData

def redir_login(html):
    # print(response.xpath('//body/script/text()')).extract()
    # print(type(response.text))
    # redir_url = 'https://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack&sudaref=weibo.com'
    redir_url = 'https://passport.weibo.com/wbsso/login?url=https%3A%2F%2Fweibo.com%2Fajaxlogin.php%3Fframelogin%3D1%26callback%3Dparent.sinaSSOController.feedBackUrlCallBack%26sudaref%3Dweibo.com&display=0&'
    w1 = 'dsplay=0&ticket='
    w2 = '&retcode='

    buff = parse.unquote(html.text)
    # buff = html.text

    print(buff)
    pat = re.compile(r'display=0&ticket=(.*?)&retcode=', re.S)
    result = pat.findall(buff)
    print(f'111111111111111')

    print(result[0])
    param = {'ticket': result[0], 'retcode': '0'}
    final_url = redir_url + urlencode(param)
    print(final_url)
    return final_url

if __name__ == '__main__':
    session = requests.session()
    session.headers = headers
    session, html = start_requests(session)     #获取5个参数的html界面
    formdata = getform(html)                    #用5个参数构造from表单

    session,html = start_requests_2(session,formdata)          #post提交form表单
    print(html.text)
    finalurl = redir_login(html)

    session,html = start_requsets_3(session,finalurl)
    print(html.text)

    html = session.get('https://weibo.com/nguide/interest')
    print(html.text)
    print(session.cookies)
    print(html.headers.__dict__)


    url = f'http://api.weibo.com/2/users/show.json?uid=6511143553&source=2835469272&callback=jQuery17206209514903843736_1564973592708&{int(time.time() * 1000)}'
    print(url)
    html = session.get(url)
    str1 = re.compile('jQuery(\d+_\d+)')
    query= str1.findall(html.text)[0]
    year = datetime.datetime.now().year
    month = datetime.datetime.now().month
    mark = 4.5


    headers ={
        'Referer':'http://travel.sina.com.cn/honghezhou_honghemilehuquanwenquan-lvyou/'
    }
    session.headers.update(headers)
    url= f'http://jingdian.travel.sina.com.cn/api/mudidi/likeMudidi?callback=jQuery{query}&id=22211&type=1&year={year}&month=2&mark=4.5&uid=6511143553&content=woaini&_={int(time.time() * 1000)}'
    html = session.get(url)
    print(html.text)